<?php
/**
 * 短消息相关识别
 */
namespace soa\ocr\baiduOcr;

class messageOcr{
    /**
     * 识别手机号，运单号
     * @param $img
     * @param string $ocrWhat
     *    $ocrWhat = 'onlyPhone' 只识别手机号
     *    $ocrWhat = 'phoneAndWaybill' 识别手机号和运单号两列
     *
     * @return array
     */
    public static function ocrPhoneAndWaybill($img, $ocrWhat='onlyPhone'){
        if(empty($img)){
            raise(1009, '没有需要识别的图像！');
        }
        $return = [];
        $retArr = baiduOcr::generalBasic($img);//百度通用文字识别（基础班）
//var_dump($retArr);
        if(//返回值正常
            isset($retArr['words_result']) &&
            !empty($retArr['words_result']) &&
            is_array($retArr['words_result'])
        ){
            if($ocrWhat=='onlyPhone'){//只识别手机号
                foreach($retArr['words_result'] as $words){
                    $return[]['phone'] = self::getPhone($words['words']);
                }
            }elseif($ocrWhat =='phoneAndWaybill'){//识别手机号和单号两列，并区分哪个在左边，哪个在右边
//var_dump($retArr['words_result']);
                $wordsArr = array_column($retArr['words_result'], 'words');
                $wordsArr = array_filter($wordsArr);
//                var_dump($wordsArr);
                if(//手机号加运单号不可能小于18位，说明手机号和运单号在两行里
                    isset($wordsArr[0]) &&
                    strlen($wordsArr[0]) < 18
                ){
                    $wordsArrChunks = array_chunk($wordsArr, 2);
                    $wordsArr = [];
                    foreach($wordsArrChunks as $chunk){
                        $wordsArr[]['words'] = isset($chunk[1]) ? $chunk[0].' '.$chunk[1] : $chunk[0];
                    }
                    $retArr['words_result'] = $wordsArr;
                }
//var_dump($wordsArr);
                foreach($retArr['words_result'] as $words){
                    $phoneAndWaybillArrTemp = self::getPhoneAndWaybill($words['words']);
                    $return[] = [
                        'type'    => $phoneAndWaybillArrTemp['type'],//type 不等于 unknow的下面手机号和单号才有效
                        'phone'   => $phoneAndWaybillArrTemp['phone'],
                        'waybill' => $phoneAndWaybillArrTemp['waybill'],
                    ];
                }
            }
        }
        return ['list'=>$return];
    }

    /**
     * 解析字符串中的手机号和运单号
     *         $words = '13312345678|7701123456789';
     *            $return = [
     *                    'phone'   => '13312345678',
     *                    'waybill' => '7701123456789',
     *                    'type'    => 'phone-waybill',
     *                ];
     *
     *
     *         $words = '7701123456789-13312345678';
     *            $return = [
     *                    'phone'   => '13312345678',
     *                    'waybill' => '7701123456789',
     *                    'type'    => 'waybill-phone',
     *                ];
     * @param $words
     * @return array
     */
    protected static function getPhoneAndWaybill($words){
        $return = [//预定义返回值
            'phone'   => '',
            'waybill' => '',
            'type'    => 'unknow',
        ];
        if(!is_string($words)){
            return $return;
        }

//        $rule = '/^((?<phone1>1\d{10})(\W*)?(?<waybill1>\w*)?)|((?<waybill2>\w*)?(\W*)?(?<phone2>1\d{10}))$/';
        $rule = '/^((?<phone1>1\d{10})([\W_]*)?(?<waybill1>[0-9A-Za-z]*)?)|((?<waybill2>[0-9A-Za-z]*)?([\W_]*)?(?<phone2>1\d{10}))$/';
        $r = preg_match_all($rule, $words, $matchs);

        if($r){
            if(isset($matchs['phone1'][0]) && $matchs['phone1'][0]){//左列手机号；右列运单号格式
                $return = [
                    'phone'   => $matchs['phone1'][0],
                    'waybill' => $matchs['waybill1'][0] ? $matchs['waybill1'][0] : '',
                    'type'    => 'phone-waybill',
                ];
            }elseif(isset($matchs['phone2'][0]) && $matchs['phone2'][0]){//左列手机号；右列运单号格式
                $return = [
                    'phone'   => $matchs['phone2'][0],
                    'waybill' => $matchs['waybill2'][0] ? $matchs['waybill2'][0] : '',
                    'type'    => 'waybill-phone',
                ];
            }
        }
        return $return;
    }

    /**
     * 匹配出字符串中的手机号  1\d{10}
     * @param $words
     * @return string
     */
    protected static function getPhone($words){
        $return = '';//预定义返回值
        if(!is_string($words)){
            return $return;
        }

        $rule = '/(?<phone>1\d{10})/';
        $r = preg_match_all($rule, $words, $matchs);

        if($r && isset($matchs['phone'][0]) && $matchs['phone'][0]){//识别到手机号
            $return = $matchs['phone'][0];
        }
        return $return;
    }




    /**
     * 测试样例
     */
    /*
    public function baiduOcrTest(){
        $url = $_GET['url'];
        echo '<img src="'.$url.'" width="300px">';
        $ret = \soa\ocr\baiduOcr\baiduOcr::generalWithLocation($url);
        var_dump($ret);
        echo '<hr>';
        $ret = \soa\ocr\baiduOcr\baiduOcr::generalBasic($url);
        var_dump($ret);
        echo '<hr>';
        $ret = \soa\ocr\baiduOcr\messageOcr::ocrPhoneAndWaybill($url, 'phoneAndWaybill');
        var_dump($ret);
        echo '<hr>';
        $ret = \soa\ocr\baiduOcr\messageOcr::ocrPhoneAndWaybill($url, 'onlyPhone');
        var_dump($ret);
    }
    */
}